<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-10-05
 * Time: 20:13
 */

namespace plugin\csauto\app\controller;

use plugin\csauto\app\common\BaseController;
use plugin\csauto\app\model\TorrentListModel;
use plugin\csauto\app\model\SiteModel;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class TorrentListController extends BaseController
{
    /**
     * @var TorrentListModel
     */
    protected $model = null;

    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct()
    {
        $this->model = new TorrentListModel;
    }

    public function index(Request $request)
    {
        return view('torrentlist/index');
    }

    /**
     * 重写 insert 方法，不支持新增数据
     *
     * @param Request $request
     * @return Response
     */
    public function insert(Request $request): Response
    {
        throw new BusinessException('TorrentList 不支持新增数据操作', 403);
    }

    /**
     * 重写 update 方法，支持编辑状态字段
     *
     * @param Request $request
     * @return Response
     */
    public function update(Request $request): Response
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);

        // 只允许更新状态字段
        $allowedFields = ['torrents_status'];
        $data = $request->only($allowedFields);

        // 验证状态值
        if (isset($data['torrents_status']) && !in_array($data['torrents_status'], [1, 2])) {
            throw new BusinessException('种子状态值无效，只能是1（待分配）或2（已分配）', 400);
        }

        if (empty($data)) {
            throw new BusinessException('未指定要更新的字段', 400);
        }

        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 404);
        }

        foreach ($data as $key => $val) {
            $model->{$key} = $val;
        }
        $model->save();

        return $this->json(0, '更新成功');
    }

    /**
     * 查询后处理数据，添加站点名称映射
     *
     * @param $items
     * @return mixed
     */
    protected function afterQuery($items)
    {
        // 获取所有站点信息用于映射
        $sites = SiteModel::pluck('site_name', 'id')->toArray();

        foreach ($items as $item) {
            // 映射站点名称
            $item->site_name = $sites[$item->site_id] ?? '未知站点';

            // 格式化状态显示
            $statusMap = [
                1 => '待分配',
                2 => '已分配'
            ];
            $item->torrents_status_text = $statusMap[$item->torrents_status] ?? '未知状态';
        }

        return $items;
    }

}
